#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cstring>
#include <unistd.h>
#include <sys/shm.h>
#include <string>

using namespace std;
const char* pathname = "/home/yss";
int proj_id = 0x66;
int defaultsize = 4096;

//转换为16进制
// string Transla(key_t key)
// {
//     char buffer[1024];
//     snprintf(buffer, sizeof(buffer), "0x%x", key);
//     return buffer;
// }

// 获取key_t
key_t getShmkey()
{
    key_t k = ftok(pathname, proj_id);//调用系统
    if(k < 0)
    {
        cerr << "key_t error, errno: " << errno << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

// 创建共享内存
int CreatshmDir(key_t k, size_t size, int flag)
{
    int shmid = shmget(k, size, flag);
    if(shmid < 0)
    {
        cerr << "shmid error, errno: " << errno << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

//创建共享内存
int Createshm(key_t k, size_t size)
{
    return CreatshmDir(k, size, IPC_EXCL | IPC_CREAT | 0666);//已经存在就出错返回
}

//获取共享内存
int Getshm(key_t k, size_t size)
{
    return CreatshmDir(k, size, IPC_CREAT);//已经存在就获取
}

//删除共享内存
void deleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if(n < 0)
    {
        cout<<"delete fail"<<endl;
    }
    else 
    {
        cout<<"delete success!"<<endl;
    }
}

//获取共享内存信息
void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if(n < 0)
    {
        cout<<"Debug fail"<<endl;
        return;
    }
    cout<<"shmds.shm_segsz: "<<shmds.shm_segsz<<endl;
    cout<<"shmds.shm_ctime: "<<shmds.shm_ctime<<endl;
    cout<<"shmds.shm_nattch: "<<shmds.shm_nattch<<endl;
    cout<<"shmds.shm_perm.__key: "<<shmds.shm_perm.__key<<endl;

}

//共享内存与进程挂接
void* ShmAttach(int shmid)
{
    void* addr = shmat(shmid, nullptr, 0);
    if((long long int)addr == -1)
    {
        cout<<"shmat fail"<<endl;
        return nullptr;
    } 
    return addr;
}

//取消挂接
void ShmDetach(void* addr)
{
    int n = shmdt(addr);
    if(n < 0)
    {
        cout<<"shmdt fail"<<endl;
    }
}